package servlet;

import bean.User;
import dao.impI.UserDaoImp;
import service.ImpI.UserServiceImpI;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//注解进行路径和servlet映射，并初始化参数(编码类型)
@WebServlet(urlPatterns = "/login",loadOnStartup = 1,
            initParams = {
                @WebInitParam(name = "encoding",value = "utf-8")
            }
)
public class LoginServlet extends HttpServlet {
    String encoding=null;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理post乱码问题
        req.setCharacterEncoding(encoding);
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //UserDaoImp userDaoImp = new UserDaoImp();
        //User user = userDaoImp.Login(username, password);
        UserServiceImpI userServiceImpI = new UserServiceImpI();
        User user = userServiceImpI.Login(username, password);
        HttpSession session = req.getSession();
        session.setAttribute("user",user);
        System.out.println(user);
        if(user==null){
            req.setAttribute("login_msg","用户名或密码错误");
            req.getRequestDispatcher("/login1.jsp").forward(req,resp);
        }else if(username.equals(user.getUsername())&&password.equals(user.getPassword())){
            req.getRequestDispatcher("/productListServlet").forward(req,resp);
        }else {
            req.setAttribute("login_msg","用户名或密码错误");
            req.getRequestDispatcher("/login1.jsp").forward(req,resp);
        }

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //获取初始化参数-编码类型
        encoding = config.getInitParameter("encoding");
    }
}
